package org.ala.tree.lsm.memtable;

import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.BiConsumer;

import org.ala.tree.lsm.KV;
import org.ala.tree.lsm.LSMConfig;

/**
 * 跳表实现的内存块
 *
 * @author ala
 * @date 2025年5月26日
 */
public class SkipListMemTable<V> extends AbstractMemTable<V> {

	
	/**
	 * 跳表
	 */
	protected ConcurrentSkipListMap<String,V> map;
	
	
	public SkipListMemTable(LSMConfig config, String id, boolean isWal) {
		super(config, id, isWal);
		map = new ConcurrentSkipListMap<>();
	}

	@Override
	public V get(String k) {
		return map.get(k);
	}

	@Override
	public void forEach(BiConsumer<String, V> consumer) {
		map.forEach(consumer);
	}

	@Override
	public boolean doPut(String k, V v) {
		return map.put(k, v) == null;
	}

	@Override
	public boolean doRemove(String k) {
		return map.remove(k) != null;
	}

	@Override
	public Iterator<KV<V>> iterator() {
		Iterator<Entry<String, V>> it = map.entrySet().iterator();
		return new Iterator<KV<V>>() {
			public boolean hasNext() {
				return it.hasNext();
			}
			public KV<V> next() {
				Entry<String, V> e = it.next();
				return KV.build(e.getKey(), e.getValue());
			}
		};
	}
	

}
